/*
 * Copyright 2022-2029 heshuixing(https://gitee.com/heshuixing)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mercury.ec.framework.air.core.client.impl.skyecho.convert;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.mercury.ec.framework.air.core.client.dto.search.flight.AirFlightRespDTO;
import com.mercury.ec.framework.air.core.client.dto.search.flight.AirFlightStopRespDTO;
import com.mercury.ec.framework.air.core.client.dto.search.flight.AirSearchFlightReqDTO;
import com.mercury.ec.framework.air.core.client.dto.search.flight.AirSearchFlightRespDTO;
import com.mercury.ec.framework.air.core.client.dto.search.price.AirPriceRespDTO;
import com.mercury.ec.framework.air.core.client.dto.search.price.AirSearchPriceReqDTO;
import com.mercury.ec.framework.air.core.client.dto.search.price.AirSearchPriceRespDTO;
import com.mercury.ec.framework.air.core.client.impl.skyecho.dto.searchflight.SkyechoClassRespDTO;
import com.mercury.ec.framework.air.core.client.impl.skyecho.dto.searchflight.SkyechoFlightRespDTO;
import com.mercury.ec.framework.air.core.client.impl.skyecho.dto.searchflight.SkyechoSearchFlightReqDTO;
import com.mercury.ec.framework.air.core.client.impl.skyecho.dto.searchflight.SkyechoSearchFlightRespDTO;
import com.mercury.ec.framework.air.core.client.impl.skyecho.util.SkyechoUtils;
import com.mercury.ec.module.air.enums.CustomerAgreementTypeEnum;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 小太阳参数转换
 *
 * @author hesx
 */
public class SkyechoConvert {
    /**
     * 转换小太阳航班查询请求参数
     *
     * @param reqDTO
     * @return
     */
    public static SkyechoSearchFlightReqDTO convertSkyechoSearchFlightReqDTO(AirSearchFlightReqDTO reqDTO) {
        SkyechoSearchFlightReqDTO skyechoSearchFlightReqDTO = new SkyechoSearchFlightReqDTO();
        if (CustomerAgreementTypeEnum.isGp(reqDTO.getCustomerAgreementType())) {
            skyechoSearchFlightReqDTO.setAirline(reqDTO.getAirlineNo());
            int length = reqDTO.getAirlineNo().split(",").length;
            StringBuffer gp = new StringBuffer("");
            for (int i = 0; i < length; i++) {
                gp.append(",GP");
            }
            skyechoSearchFlightReqDTO.setCorpFfp(gp.substring(1));
        } else if(CustomerAgreementTypeEnum.isCustomerAgreement(reqDTO.getCustomerAgreementType())) {
            skyechoSearchFlightReqDTO.setCorpFfp(reqDTO.getCustomerAgreementNo());
        }
        skyechoSearchFlightReqDTO.setTrip(reqDTO.getDepart() + reqDTO.getArrive());
        skyechoSearchFlightReqDTO.setAirDate(reqDTO.getFlightDate());
        return skyechoSearchFlightReqDTO;
    }

    /**
     * 转换小太阳航班查询请求参数（查询指定航班）
     *
     * @param reqDTO
     * @return
     */
    public static SkyechoSearchFlightReqDTO convertSkyechoSearchFlightReqDTO(AirSearchPriceReqDTO reqDTO) {
        SkyechoSearchFlightReqDTO skyechoSearchFlightReqDTO = new SkyechoSearchFlightReqDTO();
        if (CustomerAgreementTypeEnum.isGp(reqDTO.getCustomerAgreementType())) {
            skyechoSearchFlightReqDTO.setAirline(reqDTO.getAirlineNo());
            int length = reqDTO.getAirlineNo().split(",").length;
            StringBuffer gp = new StringBuffer("");
            for (int i = 0; i < length; i++) {
                gp.append(",GP");
            }
            skyechoSearchFlightReqDTO.setCorpFfp(gp.substring(1));
        } else if(CustomerAgreementTypeEnum.isCustomerAgreement(reqDTO.getCustomerAgreementType())) {
            skyechoSearchFlightReqDTO.setCorpFfp(reqDTO.getCustomerAgreementNo());
        }
        skyechoSearchFlightReqDTO.setTrip(reqDTO.getDepart() + reqDTO.getArrive());
        skyechoSearchFlightReqDTO.setAirDate(reqDTO.getFlightDate());
        skyechoSearchFlightReqDTO.setAirline(reqDTO.getAirlineNo());
        skyechoSearchFlightReqDTO.setLowestOrAll("A"); // 返回所有可用舱位
        return skyechoSearchFlightReqDTO;
    }

    /**
     * 转换标准航班查询响应参数
     *
     * @param channelId
     * @param channelName
     * @param channelType
     * @param customerAgreementType
     * @param respDTO
     * @return
     */
    public static AirSearchFlightRespDTO convertAirSearchFlightRespDTO(Long channelId, String channelName, Integer channelType, Integer customerAgreementType, SkyechoSearchFlightRespDTO respDTO) {
        AirSearchFlightRespDTO airSearchFlightRespDTO = new AirSearchFlightRespDTO();
        airSearchFlightRespDTO.setFlightDate(respDTO.getAir().getDate());
        airSearchFlightRespDTO.setDepart(respDTO.getAir().getDepart());
        airSearchFlightRespDTO.setDepartCityName(null); // todo 小太阳没有，待基础数据缓存补充
        airSearchFlightRespDTO.setArrive(respDTO.getAir().getArrive());
        airSearchFlightRespDTO.setArriveCityName(null); // todo 小太阳没有，待基础数据缓存补充
        airSearchFlightRespDTO.setUpdateTime(LocalDateTime.now());
        airSearchFlightRespDTO.setTotal(respDTO.getFlights().size());
        List<AirFlightRespDTO> flights = new ArrayList<>();
        for (SkyechoFlightRespDTO flight : respDTO.getFlights()) {
            AirFlightRespDTO airFlightRespDTO = new AirFlightRespDTO();
            airFlightRespDTO.setChannelId(channelId);
            airFlightRespDTO.setChannelName(channelName);
            airFlightRespDTO.setChannelType(channelType);
            airFlightRespDTO.setAirlineNo(flight.getAirCode());
            airFlightRespDTO.setAirlineName(null); // todo 小太阳没有，待基础数据缓存补充
            airFlightRespDTO.setCarrierAirlineNo(flight.getShareNum());
            airFlightRespDTO.setCarrierAirlineName(null); // todo 小太阳没有，待基础数据缓存补充
            airFlightRespDTO.setFlightNo(flight.getFlightNum());
            airFlightRespDTO.setCarrierFlightNo(flight.getShareNum());
            airFlightRespDTO.setDepart(flight.getDepartCity());
            airFlightRespDTO.setDepartAirportName(null); // todo 小太阳没有，待基础数据缓存补充
            airFlightRespDTO.setArrive(flight.getArriveCity());
            airFlightRespDTO.setArriveAirportName(null); // todo 小太阳没有，待基础数据缓存补充
            airFlightRespDTO.setDepartTerminal(flight.getDepartAirport());
            airFlightRespDTO.setArriveTerminal(flight.getArriveAirport());
            airFlightRespDTO.setDepartTime(SkyechoUtils.getFlightTime(flight.getDepart()));
            airFlightRespDTO.setArriveTime(SkyechoUtils.getFlightTime(flight.getArrive()));
            airFlightRespDTO.setAirModel(flight.getEquip());
            airFlightRespDTO.setAirModelName(flight.getEquip());
            airFlightRespDTO.setHaveFood(StrUtil.isNotBlank(flight.getFood()));
            airFlightRespDTO.setFoodType(SkyechoUtils.getFoodType(flight.getFood()));
            airFlightRespDTO.setShare("Y".equals(flight.getIsShare()));
            airFlightRespDTO.setThrough(StrUtil.isNotBlank(flight.getTcfNo()));
            airFlightRespDTO.setStop(flight.getStop() == 1);
            if (flight.getStop() == 1) {
                List<AirFlightStopRespDTO> stops = new ArrayList<>();
                AirFlightStopRespDTO airFlightStopRespDTO = new AirFlightStopRespDTO();
                airFlightStopRespDTO.setStopStartDate(null);
                airFlightStopRespDTO.setStopEndDate(null);
                airFlightStopRespDTO.setStopStartTime(null);
                airFlightStopRespDTO.setStopEndTime(null);
                airFlightStopRespDTO.setStopCityName(flight.getStopcity());
                airFlightStopRespDTO.setStopAirportNo(null);
                airFlightStopRespDTO.setStopTerminal(null);
                airFlightRespDTO.setStops(stops);
            }
            airFlightRespDTO.setPunctualityRate(BigDecimal.ZERO);
            airFlightRespDTO.setDistance(respDTO.getAir().getTpm());
            airFlightRespDTO.setFlightDays(SkyechoUtils.getFlightDays(airFlightRespDTO.getDepartTime(), airFlightRespDTO.getArriveTime()));
            airFlightRespDTO.setFlightTimes(null);
            airFlightRespDTO.setAirportTax(flight.getTax());
            airFlightRespDTO.setOilTax(flight.getYq());
            // 取航班最低价舱位
            List<SkyechoClassRespDTO> classes = flight.getClasses();
            if (CollUtil.isNotEmpty(classes)) {
                classes = classes.stream().filter(p -> p.getPrice() != null).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(classes)) {
                    Collections.sort(classes, Comparator.comparing(SkyechoClassRespDTO::getPrice));
                    SkyechoClassRespDTO skyechoClassRespDTO = classes.get(0);
                    airFlightRespDTO.setCustomerAgreementType(customerAgreementType);
                    airFlightRespDTO.setDiscount(skyechoClassRespDTO.getDiscount());
                    airFlightRespDTO.setLowestPrice(skyechoClassRespDTO.getPrice());
                    flights.add(airFlightRespDTO);
                }
            }
        }
        airSearchFlightRespDTO.setFlights(flights);
        return airSearchFlightRespDTO;
    }

    /**
     * 转换标准运价查询响应参数
     *
     * @param channelId
     * @param channelName
     * @param channelType
     * @param airlineNo
     * @param flightNo
     * @param customerAgreementType
     * @param respDTO
     * @return
     */
    public static AirSearchPriceRespDTO convertAirSearchPriceRespDTO(Long channelId, String channelName, Integer channelType, String airlineNo, String flightNo, Integer customerAgreementType, SkyechoSearchFlightRespDTO respDTO) {
        AirSearchPriceRespDTO airSearchPriceRespDTO = new AirSearchPriceRespDTO();
        airSearchPriceRespDTO.setUpdateTime(LocalDateTime.now());
        // 航班去重
        List<SkyechoFlightRespDTO> flights = respDTO.getFlights();
        flights = flights.stream().filter(p -> airlineNo.equals(p.getAirCode()) && flightNo.equals(p.getFlightNum())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(flights)) {
            flights = flights.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(p -> p.getAirCode() + p.getFlightNum()))), ArrayList::new));
            SkyechoFlightRespDTO skyechoFlightRespDTO = flights.stream().findFirst().get();
            List<SkyechoClassRespDTO> classes = skyechoFlightRespDTO.getClasses();
            classes = classes.stream().filter(p -> p.getPrice() != null).collect(Collectors.toList());
            airSearchPriceRespDTO.setTotal(classes.size());
            List<AirPriceRespDTO> prices = new ArrayList<>();
            for (SkyechoClassRespDTO skyechoClassRespDTO : classes) {
                AirPriceRespDTO airPriceRespDTO = new AirPriceRespDTO();
                airPriceRespDTO.setChannelId(channelId);
                airPriceRespDTO.setChannelName(channelName);
                airPriceRespDTO.setChannelType(channelType);
                airPriceRespDTO.setProductName(null);
                airPriceRespDTO.setProductType(null);
                airPriceRespDTO.setProductProperty(null);
                airPriceRespDTO.setPolicyId(skyechoClassRespDTO.getSaleCode());
                airPriceRespDTO.setPolicyType(null);
                airPriceRespDTO.setCabin(skyechoClassRespDTO.getCode());
                airPriceRespDTO.setCabinCount(skyechoClassRespDTO.getStatus());
                airPriceRespDTO.setCabinType(skyechoClassRespDTO.getService_Code());
                airPriceRespDTO.setCabinTypeName(skyechoClassRespDTO.getService_Code());
                airPriceRespDTO.setPublicPrice(skyechoClassRespDTO.getPublicPrice());
                airPriceRespDTO.setPrice(skyechoClassRespDTO.getPrice());
                airPriceRespDTO.setPriceSource(skyechoClassRespDTO.getPriceType());
                airPriceRespDTO.setCustomerAgreementType(customerAgreementType);
                airPriceRespDTO.setDiscount(skyechoClassRespDTO.getDiscount());
                airPriceRespDTO.setDiscountPrice(skyechoClassRespDTO.getPfPrice());
                airPriceRespDTO.setChildPrice(skyechoClassRespDTO.getPriceC());
                airPriceRespDTO.setChildPriceSource(skyechoClassRespDTO.getPriceTypeC());
                airPriceRespDTO.setBabyPrice(skyechoClassRespDTO.getPriceB());
                airPriceRespDTO.setBabyPriceSource(skyechoClassRespDTO.getPriceTypeB());
                airPriceRespDTO.setBookingKey(IdWorker.getIdStr());
                airPriceRespDTO.setBookingSecret(IdWorker.getIdStr());
                prices.add(airPriceRespDTO);
            }
            airSearchPriceRespDTO.setPrices(prices);
        }
        return airSearchPriceRespDTO;
    }
}
